package com.evaluation.kexingcp.psycho.evaluation.sys.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.kexingcp.admin.api.entity.SysTenant;
import com.evaluation.kexingcp.admin.service.SysTenantService;
import com.evaluation.kexingcp.common.core.util.R;
import com.evaluation.kexingcp.common.data.tenant.TenantContextHolder;
import com.evaluation.kexingcp.common.excel.annotation.ResponseExcel;
import com.evaluation.kexingcp.common.log.annotation.SysLog;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationQuestionsEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationScaleEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationTenantTypesEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationQuestionsService;
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationScaleService;
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationTenantTypesService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 测评量表
 *
 * @author 九炜
 * @date 2024-07-01 09:52:50
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/evaluationScale" )
@Tag(description = "evaluationScale" , name = "测评量表管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class EvaluationScaleController {

    private final EvaluationScaleService evaluationScaleService;

    private final EvaluationTenantTypesService evaluationTenantTypesService;
    private final EvaluationQuestionsService evaluationQuestionsService;

    private final SysTenantService sysTenantService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param evaluationScale 测评量表
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('evaluation_evaluationScale_view')" )
    public R getEvaluationScalePage(@ParameterObject Page page, @ParameterObject EvaluationScaleEntity evaluationScale) {
        LambdaQueryWrapper<EvaluationScaleEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.like(StrUtil.isNotBlank(evaluationScale.getScaleName()),EvaluationScaleEntity::getScaleName,evaluationScale.getScaleName());
		wrapper.like(StrUtil.isNotBlank(evaluationScale.getEnglishName()),EvaluationScaleEntity::getEnglishName,evaluationScale.getEnglishName());
		wrapper.eq(StrUtil.isNotBlank(evaluationScale.getScaleVersion()),EvaluationScaleEntity::getScaleVersion,evaluationScale.getScaleVersion());
		wrapper.eq(StrUtil.isNotBlank(evaluationScale.getScaleWarning()),EvaluationScaleEntity::getScaleWarning,evaluationScale.getScaleWarning());

        return R.ok(evaluationScaleService.page(page, wrapper));
    }

    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page2" )
    public R getEvaluationScalePage2(@ParameterObject Page page, @ParameterObject EvaluationScaleEntity evaluationScale) {
        LambdaQueryWrapper<EvaluationScaleEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StrUtil.isNotBlank(evaluationScale.getScaleName()),EvaluationScaleEntity::getScaleName,evaluationScale.getScaleName());
        wrapper.like(StrUtil.isNotBlank(evaluationScale.getEnglishName()),EvaluationScaleEntity::getEnglishName,evaluationScale.getEnglishName());
        wrapper.eq(StrUtil.isNotBlank(evaluationScale.getScaleVersion()),EvaluationScaleEntity::getScaleVersion,evaluationScale.getScaleVersion());
        wrapper.eq(StrUtil.isNotBlank(evaluationScale.getScaleWarning()),EvaluationScaleEntity::getScaleWarning,evaluationScale.getScaleWarning());

        if (StringUtils.isNotEmpty(evaluationScale.getTenantType())) {
            EvaluationTenantTypesEntity tenantTypesEntity = evaluationTenantTypesService
                    .getOne(Wrappers.lambdaQuery(EvaluationTenantTypesEntity.class)
                            .eq(EvaluationTenantTypesEntity::getName, evaluationScale.getTenantType()));

            List<String> scaleIds = JSON.parseArray(tenantTypesEntity.getScales(), String.class);
            wrapper.in(EvaluationScaleEntity::getId, scaleIds);
        }

        return R.ok(evaluationScaleService.page(page, wrapper));
    }

    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/scaleQuestion" )
    @PreAuthorize("@pms.hasPermission('evaluation_scaleQuestion_view')")
    public R getEvaluationScalePage3(@ParameterObject Page page, @ParameterObject EvaluationScaleEntity evaluationScale) {
        LambdaQueryWrapper<EvaluationScaleEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StrUtil.isNotBlank(evaluationScale.getScaleName()),EvaluationScaleEntity::getScaleName,evaluationScale.getScaleName());
        wrapper.like(StrUtil.isNotBlank(evaluationScale.getEnglishName()),EvaluationScaleEntity::getEnglishName,evaluationScale.getEnglishName());
        wrapper.eq(StrUtil.isNotBlank(evaluationScale.getScaleVersion()),EvaluationScaleEntity::getScaleVersion,evaluationScale.getScaleVersion());
        wrapper.eq(StrUtil.isNotBlank(evaluationScale.getScaleWarning()),EvaluationScaleEntity::getScaleWarning,evaluationScale.getScaleWarning());


        SysTenant tenant = sysTenantService.getById(TenantContextHolder.getTenantId());
        EvaluationTenantTypesEntity tenantTypesEntity = evaluationTenantTypesService
                .getOne(Wrappers.lambdaQuery(EvaluationTenantTypesEntity.class)
                        .eq(EvaluationTenantTypesEntity::getName, tenant.getOrgType()));
        List<String> scaleIds = JSON.parseArray(tenantTypesEntity.getScales(), String.class);
        wrapper.in(EvaluationScaleEntity::getId, scaleIds);

        IPage<EvaluationScaleEntity> scales = evaluationScaleService.page(page, wrapper);
        scales.convert(scale -> {
            scale.setQuestions(evaluationQuestionsService.list(Wrappers.lambdaQuery(EvaluationQuestionsEntity.class).eq(EvaluationQuestionsEntity::getScaleId, scale.getId())));
            return scale;
        });
        return R.ok(scales);
    }

    /**
     * 通过id查询测评量表
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(evaluationScaleService.getById(id));
    }

    /**
     * 新增测评量表
     * @param evaluationScale 测评量表
     * @return R
     */
    @Operation(summary = "新增测评量表" , description = "新增测评量表" )
    @SysLog("新增测评量表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('evaluation_evaluationScale_add')" )
    public R save(@RequestBody EvaluationScaleEntity evaluationScale) {
        return R.ok(evaluationScaleService.save(evaluationScale));
    }

    /**
     * 修改测评量表
     * @param evaluationScale 测评量表
     * @return R
     */
    @Operation(summary = "修改测评量表" , description = "修改测评量表" )
    @SysLog("修改测评量表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('evaluation_evaluationScale_edit')" )
    public R updateById(@RequestBody EvaluationScaleEntity evaluationScale) {
        return R.ok(evaluationScaleService.updateById(evaluationScale));
    }

    /**
     * 通过id删除测评量表
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除测评量表" , description = "通过id删除测评量表" )
    @SysLog("通过id删除测评量表" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('evaluation_evaluationScale_del')" )
    public R removeById(@RequestBody Long[] ids) {
        // 联动删除
        return R.ok(evaluationScaleService.removeBatchByIds(CollUtil.toList(ids)));
    }


    /**
     * 导出excel 表格
     * @param evaluationScale 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('evaluation_evaluationScale_export')" )
    public List<EvaluationScaleEntity> export(EvaluationScaleEntity evaluationScale,Long[] ids) {
        return evaluationScaleService.list(Wrappers.lambdaQuery(evaluationScale).in(ArrayUtil.isNotEmpty(ids), EvaluationScaleEntity::getId, ids));
    }
}